package cn.itcast.fore.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.crm.domain.Customer;
import cn.itcast.fore.util.MailUtils;
import cn.itcast.fore.action.BaseAction;

/** 
 * 用户的控制层
 *
 * @author Shao-Fei Fan 
 * @version 1.0,2017年9月10日 上午11:03:20 
 */
@Controller
@Scope("prototype")
@ParentPackage("json-default")
@Namespace("/")
public class CustomerAction extends BaseAction<Customer>  {
	
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@Action(value="customer_sendSms")
	public String sendSms(){
		final String randomCode = RandomStringUtils.randomNumeric(4);
		System.out.println("短信验证码是:"+randomCode);
		// 将短信验证码保存到session中
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		
		// 调用mq服务，发送一条信息
		jmsTemplate.send("bos_sms",new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msg", randomCode);
				return mapMessage;
			}
		});
		
		return NONE;
	}
	
	// 获得验证码
	private String checkcode;
	
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Action(value="customer_regidt",results={@Result(name="error",location="./signup.html",type="redirect"),
			@Result(name="success",location="./signup-success.html",type="redirect")})
	public String regidt(){
		String sessionCheckcode = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if((sessionCheckcode==null) ||(!sessionCheckcode.equals(checkcode)) ){
			// 验证码错误
			return "error";
		}else{
			// 发送远程数据保存客户信息
			WebClient.create("http://localhost:9002/crm_management/services/customerService/customer").
			type(MediaType.APPLICATION_JSON).post(model);
			
			// 发送验证邮件
			// 生成激活码，保存到redis
			String activecode = RandomStringUtils.randomNumeric(32);
			System.out.println(model.getTelephone());
			redisTemplate.opsForValue().set(model.getTelephone(),activecode ,24,TimeUnit.HOURS);
			
			String content ="尊敬的客户，请您尽快点击完成邮箱激活，激活码将在24小时后失效:<br/><a href=" + MailUtils.activeUrl
					+"?telephone="+model.getTelephone()
					+ "&activecode=" + activecode + ">'速运快递邮箱绑定'"
					+ "</a>";
			MailUtils.sendMail("速运邮箱绑定", content, model.getEmail());
			return SUCCESS;
			}
	}
	
	
	// 实现邮箱的激活
	
	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}
	
	
	@Action("customer_activeMail")
	public String activeMail() throws IOException{
		
		// 设置编码
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		
		// 判断激活码是否有效
		String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		System.out.println(activecodeRedis);
		if(activecodeRedis==null || !activecodeRedis.equals(activecode)){
			ServletActionContext.getResponse().getWriter().println("激活码无效，请重新绑定邮箱");
		}else{
			System.out.println("到这了");
			// 激活码有效
			// 防止重复绑定
			// 调用 crm webservice 查询客户信息判断是否已绑定
											// http://localhost:9002/crm_management/services/customerService/customer
			Customer customer = WebClient.create("http://localhost:9002/crm_management/services/customerService/customer/telephone/"
					+model.getTelephone()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if(customer.getType()==null || customer.getType()!=1){
				//没有绑定
				 WebClient.create("http://localhost:9002/crm_management/services/customerService/customer/updatetype/"
							+model.getTelephone()).get();
				 ServletActionContext.getResponse().getWriter().println("绑定成功");
			}else{
				ServletActionContext.getResponse().getWriter().println("邮箱已经绑定，无需再绑定");
			}
			redisTemplate.delete(model.getTelephone());
		}
		return NONE;
	}
	
	
}
